﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foothill.Bus.Node;
using Foothill.Persistent.Command;
using Foothill.Bus.Result;
using Foothill.Utils;

namespace GGFW.DataAccess.Constants
{
    /// <summary>
    /// sql语句工具类
    /// </summary>
    public class SqlUtil
    {
        /// <summary>
        /// 组成排序order by sql语句
        /// </summary>
        /// <param name="orderField">排序字段</param>
        /// <param name="orderDirection">排序方式(asc/desc)</param>
        /// <param name="defaultField">默认排序字段</param>
        /// <param name="defaultDirection">默认排序方式</param>
        /// <returns></returns>
        public static string GetOrderSql(string orderField, string orderDirection, string defaultField, string defaultDirection)
        {
            string orderSql = " Order by ";
            if (!string.IsNullOrEmpty(orderField))
            {
                orderSql += orderField;
            }
            else
            {
                orderSql += " " + defaultField; //默认以记录创建时间排序
            }

            if (!string.IsNullOrEmpty(orderDirection))
            {
                orderSql += " " + orderDirection;
            }
            else
            {
                orderSql += " " + defaultDirection; //默认为降序
            }

            return orderSql;
        }

        /// <summary>
        /// 获得符合条件的查询结果总数
        /// </summary>
        /// <param name="querySql">查询Sql语句</param>
        /// <returns>结果总数</returns>
        public static int GetQueryCount(string querySql)
        {
            string sql = string.Format("select count(0) as RecordCount from({0}) as counttmp", querySql);


            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("", sql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0 && result.Records[0].Fields.Count > 0)
            {
                int count = NumericUtil.toInteger(result.Records[0].Fields[0].FieldValue, -1);

                return count;
            }

            return -1;
        }
    }
}
